import React from 'react'
import modelExtend from 'dva-model-extend'
import { findByOrg, addWithOrg, update, enable, disable } from 'services/distributor'
import { queryUserByKeywords } from 'services/security/user'
import { lwjPageModel } from 'utils/model'
import { Modal, message } from 'antd'
import { bindUserRoles, getUserRoles, query } from 'services/security/role'

export default modelExtend(lwjPageModel, {
  namespace: 'bindUser',
  state: {
    user: {},
    modalVisible: false,
    step: 0,
    roleIds: [],
    roles: [],
    rolesModalVisible: false,
  },
  subscriptions: {
    setup({ dispatch, history }) {

    },
  },
  effects: {
    * findUser({ payload }, { call, put }) {
      const res = yield call(queryUserByKeywords, payload.keyword)
      if (!res.success) {
        return
      }
      yield put({
        type: 'setUser', payload: res.result
      })
    },

    * stepUserNew({ payload }, { select, call, put }) {
      const res = yield call(queryUserByKeywords, payload.keyword)
      if (!res.success) {
        return
      }
      yield put({
        type: 'setUser', payload: res.result
      })
      const users = yield select(({ userManage }) => userManage.users);
      const currentDistributor = yield select(({ userManage }) => userManage.currentItem);
      let userIds = [];
      if (res.result.enabled) {
        Modal.error({
          title: '错误',
          content: '该用户已被禁用，请在系统用户中启用后再进行绑定'
        })
        return
      }
      users.forEach(element => {
        userIds.push(element.id)
      });
      debugger;
      if (userIds.includes(res.result.id)) {
        Modal.error({
          title: '错误',
          content: '该用户已在' + currentDistributor.organizationName + '中存在，不允许重复绑定'
        })
        return
      }
      yield put({
        type: 'role/query', payload: { limit: 30 }
      })
      yield put({
        type: 'setStep', payload: "increment"
      })

    },

    * onBindRoles({ payload }, { call, put }) {
      const { userId, orgId } = payload
      // 获取roles
      const roles = (yield call(query, { order: 'DESC', queryParam: { limit: 30 } })).items
      // 获取此人已经绑定的roleIds
      const userRoles = (yield call(getUserRoles, userId)).result
      // 处理roles，拿到id
      let roleIds = userRoles.map(item => item.id)
      // "ROLE_STORE_SALESMAN" "ROLE_STORE_EMPLOYEE"
      if (!userRoles.some(item => item.name === 'ROLE_STORE_SALESMAN')) {
        let salesman = roles.find(item => item.name === 'ROLE_STORE_SALESMAN')
        roleIds.push(salesman.id)
      }
      if (!userRoles.some(item => item.name === 'ROLE_STORE_EMPLOYEE')) {
        let employee = roles.find(item => item.name === 'ROLE_STORE_EMPLOYEE')
        roleIds.push(employee.id)
      }
      const res = yield call(bindUserRoles, userId, roleIds)
      console.log(res)
      if (res.success) {
        yield put({ type: 'userManage/onBindUser', payload: { id: orgId, ids: [userId] } })
        yield put({ type: 'hideModal' })
        yield put({ type: 'bindRoleIds', payload: { roleIds: [] } })
        message.success('成功绑定系统的 门店员工 及 门店销售 角色', 5);
      }
    },
  },
  reducers: {
    setStep(state, { payload }) {
      switch (payload) {
        case 'increment':
          state.step += 1
          break
        case 'decrement':
          if (state.step > 0) {
            state.step -= 1
          }

          if (state.step === 0) {
            state.user = {}
          }
          break
        default:

      }

      return {
        ...state
      }
    },

    setUser(state, { payload }) {
      state.user = payload

      return {
        ...state
      }
    },

    showModal(state, { payload }) {
      state.modalVisible = true
      state.step = 0
      return {
        ...state
      }
    },

    hideModal(state, { payload }) {
      state.modalVisible = false

      return {
        ...state
      }
    },

    destroyUser(state, { payload }) {
      state.user = {}
      state.step = 0

      return {
        ...state
      }
    },

    bindRoleIds(state, { payload }) {
      state.roleIds = payload.roleIds

      return {
        ...state
      }
    },

    showRolesModal(state, { payload }) {
      state.rolesModalVisible = payload
      return {
        ...state
      }
    },
  },
})
